package com.xxd.rpt2.config

import com.xxd.rpt2.Entity.Role
import com.xxd.rpt2.Entity.User
import com.xxd.rpt2.service.UserService
import com.xxd.rpt2.vo.JwtToken
import com.xxd.utils.JwtUtil
import org.apache.shiro.authc.*
import org.apache.shiro.authz.AuthorizationInfo
import org.apache.shiro.authz.SimpleAuthorizationInfo
import org.apache.shiro.realm.AuthorizingRealm
import org.apache.shiro.subject.PrincipalCollection
import org.springframework.beans.factory.annotation.Autowired

class JwtRealm extends AuthorizingRealm {

    @Autowired
    UserService userService

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return new SimpleAuthorizationInfo();
    }

    /**
     * 验证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken)token
        String tokenStr = jwtToken.getToken()
        User user = userService.findByName(JwtUtil.getUserName(tokenStr))
        if(user){
            AuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user,user.getPassword(),user.getCredentialsSalt(),getName())
            return simpleAuthenticationInfo
        }
        return null
    }
}
